﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using ECS.DAL;
using ECS.Framework;
namespace E_ICS.E_ICS
{
    public partial class frmTransactionHistory : Form
    {
        #region private properties
        DataSet transactionHis;
        DataTable transactionTW;
        string tran_type, sub_tran_type,trandate,description, mawb, hawb,pieces,net,carrier,flt_no, flt_date, nog, scaleID, slip_no,loc,username,device,agent;
        string stvalidationMMHH = "PASS";
        string newdate;
        #endregion
        public frmTransactionHistory()
        {
            InitializeComponent();
        }
        #region form event
        private void btnSearch_Click(object sender, EventArgs e)
        {
            validationMMHH(txtDateFrom);
            validationMMHH(txtDateTo);
            DateTime date;
            if (!string.IsNullOrEmpty(txtFltdate.Text))
            {
                if (DateTime.TryParse(txtFltdate.Text, out date) == false)
                {
                    CommonMessageBox.ShowMessageWarning("Flightdate format is not correct.");
                    txtFltdate.Focus();
                    return;
                }
            }
            if(stvalidationMMHH.Equals("PASS"))
            {
                SearchTransaction(GlobalVariable.user.ApplicationID, GlobalVariable.Device, GlobalVariable.user.UserID);
            }
            else

            //คืนค่า
            {
                stvalidationMMHH = "PASS";
            }
        }
        private void btnClearAll_Click(object sender, EventArgs e)
        {
            clearAll();
        }
        private void frmTransactionHistory_Load(object sender, EventArgs e)
        {
            this.toolStripStatusLabel2.Text = GlobalVariable.userName;
            dpkFromDate.Enabled = false;
            dpkToDate.Enabled = false;
            txtDateTo.Enabled = false;
            txtDateFrom.Enabled = false;
            imbCD.Enabled = false;
            imbPD.Enabled = false;
            imbPH.Enabled = false;
            dgvTransaction.RowHeadersWidth = 80;
        }
        private void chkDataSearch_CheckedChanged(object sender, EventArgs e)
        {
            if (chkDataSearch.Checked)
            {
                dpkFromDate.Enabled = true;
                dpkToDate.Enabled = true;
                txtDateTo.Enabled = true;
                txtDateFrom.Enabled = true;
                imbCD.Enabled = true;
                imbPD.Enabled = true;
                imbPH.Enabled = true;
            }
            else
            {
                dpkFromDate.Enabled = false;
                dpkToDate.Enabled = false;
                txtDateTo.Enabled = false;
                txtDateFrom.Enabled = false;
                imbCD.Enabled = false;
                imbPD.Enabled = false;
                imbPH.Enabled = false;
            }
        }
        private void dgvTransaction_Sorted(object sender, EventArgs e)
        {
            setRowNumber(dgvTransaction);
        }
        private void dpkFlightDate_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                txtFltdate.Text = String.Format("{0:ddMMMyy}", dpkFlightDate.Value).ToUpper();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void imbPH_Click(object sender, EventArgs e)
        {
            try
            {
                set_PHtime_to_dpk();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void imbPD_Click(object sender, EventArgs e)
        {
            try
            {
                set_PDtime_to_dpk();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void imbCD_Click(object sender, EventArgs e)
        {
            try
            {
                set_CDtime_to_dpk();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        #endregion
        #region private method
        private void SearchTransaction(string appId,string device, string userId)
        {
            try
            {
                transactionHis = new DataSet();
                using (Entities entity = new Entities())
                {
                    entity.Open();
                    DbCommand cmd = entity.CreateCommand("usp_SearchTranLogWithDate");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchApplicationID", appId));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchMAWB", txtPrefix.Text + "-" +txtSerial.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchMAWBPrefix", txtPrefix.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchMAWBSerial", txtSerial.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchHAWB", txtHAWB.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchCarrier", txtCarrier.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchFlightNumber", txtFltNo.Text));
                    if (!string.IsNullOrEmpty(txtFltdate.Text))
                    {
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtFlightDate", Convert.ToDateTime(txtFltdate.Text)));
                    }
                    else
                    {
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtFlightDate", null));
                    }
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchAgentCode", txtAgentCode.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchAgentName", txtAgentName.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchScaleID", txtScaleID.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchStationID", txtStationID.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchSlipNumber", txtSlipNumber.Text));
                    if (chkDataSearch.Checked)
                    {
                        DateTime dateFrom = dpkFromDate.Value;
                        string datedpkfrom = dateFrom.Date.ToString("yyyy-MM-dd");
                        ConvertDate(datedpkfrom);
                        string allfromdate = newdate + " " + txtDateFrom.Text;
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtFromDateTime", allfromdate));

                        DateTime dateto = dpkToDate.Value;
                        string datedpkto = dateto.Date.ToString("yyyy-MM-dd");
                        ConvertDate(datedpkto);
                        string alltodate = newdate + " " + txtDateTo.Text;
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtToDateTime", alltodate));
                    }
                    else
                    {
                        
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtFromDateTime", null));
                        cmd.Parameters.Add(entity.CreateParameter("@in_dtToDateTime", null));
                    }
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchLocation",txtLocation.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchSearchUserID",txtUserID.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchSearchDevice",txtDevice.Text));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchDevice", device));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchUserID", userId));
                    DbDataAdapter adapter = entity.CreateDataAdapter(cmd);
                    adapter.Fill(transactionHis);
                }
                transactionTW = new DataTable();
                transactionTW = CreateTransaction_TB(transactionHis);
                dgvTransaction.DataSource = transactionTW;
                setRowNumber(dgvTransaction);
                if (dgvTransaction.Rows.Count>0)
                {
                    setdgvTransaction();
                }
                else
                {
                    CommonMessageBox.ShowMessageWarning("Data not found");
                }
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void setdgvTransaction()
        {
            dgvTransaction.RowHeadersWidth = 60;
            dgvTransaction.Columns[0].Width=80;
            dgvTransaction.Columns[1].Width = 80;
            dgvTransaction.Columns[6].Width = 50;
            dgvTransaction.Columns[7].Width = 50;
            dgvTransaction.Columns[8].Width = 50;
            dgvTransaction.Columns[9].Width = 50;
            dgvTransaction.Columns[10].Width = 70;
            dgvTransaction.Columns[12].Width = 70;
            dgvTransaction.Columns[13].Width = 70;
            dgvTransaction.Columns[14].Width = 70;
          
        }
        private DataTable CreateTransaction_TB(DataSet ds)
        {
            DataTable Transaction = new DataTable();
            ///////////create head column/////////////////
            Transaction.Columns.Add("Transaction Type", typeof(string));    //0
            Transaction.Columns.Add("Sub Transaction Type", typeof(string)); //1
            Transaction.Columns.Add("Transaction Date", typeof(string));    //2
            Transaction.Columns.Add("Description", typeof(string));         //3
            Transaction.Columns.Add("MAWB", typeof(string));                //4
            Transaction.Columns.Add("HAWB", typeof(string));                //5
            Transaction.Columns.Add("Piece", typeof(string));               //6
            Transaction.Columns.Add("Weight", typeof(string));              //7
            Transaction.Columns.Add("Carrier", typeof(string));             //8
            Transaction.Columns.Add("Flight No", typeof(string));           //9
            Transaction.Columns.Add("Flight Date", typeof(string));         //10
            Transaction.Columns.Add("Nature of Goods", typeof(string));     //11
            Transaction.Columns.Add("Scale ID", typeof(string));            //12
            Transaction.Columns.Add("Slip Number", typeof(string));         //13
            Transaction.Columns.Add("Location",typeof(string));             //14
            Transaction.Columns.Add("Agent", typeof(string));               //15
            Transaction.Columns.Add("UserID", typeof(string));              //16
            Transaction.Columns.Add("Device", typeof(string));              //17
            ///////////////////////////////////////////////
            int row = transactionHis.Tables[0].Rows.Count;
            for (int i = 0; i < row; i++)
            {
                tran_type = transactionHis.Tables[0].Rows[i]["tran_type"].ToString().Trim();
                sub_tran_type = transactionHis.Tables[0].Rows[i]["sub_tran_type"].ToString().Trim();
                trandate = transactionHis.Tables[0].Rows[i]["start_tran_datetime"].ToString().Trim();
                description = transactionHis.Tables[0].Rows[i]["description"].ToString().Trim();
                mawb = transactionHis.Tables[0].Rows[i]["display_mawb"].ToString().Trim();
                hawb = transactionHis.Tables[0].Rows[i]["hawb"].ToString().Trim();
                pieces = transactionHis.Tables[0].Rows[i]["piece_count"].ToString().Trim();
                net = transactionHis.Tables[0].Rows[i]["net_weight"].ToString().Trim();
                carrier = transactionHis.Tables[0].Rows[i]["carrier"].ToString().Trim();
                flt_no = transactionHis.Tables[0].Rows[i]["flight_number"].ToString().Trim();
                flt_date = transactionHis.Tables[0].Rows[i]["display_flight_date"].ToString().Trim();
                nog = transactionHis.Tables[0].Rows[i]["nature_of_goods"].ToString().Trim();
                scaleID = transactionHis.Tables[0].Rows[i]["scale_id"].ToString().Trim();
                slip_no = transactionHis.Tables[0].Rows[i]["slip_number"].ToString().Trim();
                loc = transactionHis.Tables[0].Rows[i]["location"].ToString().Trim();
                agent = transactionHis.Tables[0].Rows[i]["agent_code"].ToString().Trim();
                username = transactionHis.Tables[0].Rows[i]["user_id"].ToString().Trim();
                device = transactionHis.Tables[0].Rows[i]["device"].ToString().Trim();
                Transaction.Rows.Add(tran_type, sub_tran_type, trandate, description, mawb, hawb, pieces, net, carrier, flt_no, flt_date, nog, scaleID, slip_no, loc, agent, username, device);
            }
            return Transaction;
        }
        private void setRowNumber(DataGridView dgv)
        {
            try
            {
                // dgvWeight_Disp.
                //dgv.RowHeadersWidth = 100;
                //dgvWeight_Disp.Columns[-1].HeaderText = "No";
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (row.Index == dgv.Rows.Count )
                    {
                        row.HeaderCell.Value = "";
                    }
                    else
                    {
                        row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
                    }
                }
            }
            catch 
            {
                
               // throw;
            }      
        }
        private void set_PHtime_to_dpk()
        {

            //เช็ค Datetime nows            
            DateTime Dateto = DateTime.Now;


            // เอาเวลาปัจจุบัน ลบ 1ชั่วโมง(เพราะจะหาค่าชั่วโมงที่แล้ว
            System.TimeSpan duration = new System.TimeSpan(0, -1, 0, 0);
            System.DateTime dateFromnow = Dateto.Add(duration);

            //เอาวันทีใส่ datepicker
            dpkFromDate.Value = dateFromnow;
            dpkToDate.Value = Dateto;

            //เอาเวลาใส่ datepicker

            //แปลง datetime now เป็น string   
            string sttimeFromnow = dateFromnow.ToString("HH:mm");
            string sttimetonow = Dateto.ToString("HH:mm");
            //เอาstring ลง textbox
            txtDateFrom.Text = sttimeFromnow;
            txtDateTo.Text = sttimetonow;

        }

        private void set_CDtime_to_dpk()
        {

            //เช็ค Datetime nows            
            DateTime Dateto = DateTime.Now;


            //เอาวันทีใส่ datepicker
            dpkFromDate.Value = Dateto;
            dpkToDate.Value = Dateto;

            //เอาเวลาใส่ datepicker

            //แปลง datetime now เป็น string   
            string sttimeFromnow = "00:00";
            string sttimetonow = Dateto.ToString("HH:mm");
            //เอาstring ลง textbox
            txtDateFrom.Text = sttimeFromnow;
            txtDateTo.Text = sttimetonow;

        }

        private void set_PDtime_to_dpk()
        {

            //เช็ค Datetime nows            
            DateTime Dateto = DateTime.Now;


            // เอาเวลาปัจจุบัน ลบ 1ชั่วโมง(เพราะจะหาค่าชั่วโมงที่แล้ว
            System.TimeSpan duration = new System.TimeSpan(-1, 0, 0, 0);
            System.DateTime dateFromnow = Dateto.Add(duration);

            //เอาวันทีใส่ datepicker
            dpkFromDate.Value = dateFromnow;
            dpkToDate.Value = dateFromnow;

            //เอาเวลาใส่ datepicker

            //แปลง datetime now เป็น string   
            string sttimeFromnow = "00:00";
            string sttimetonow = "23:59";
            //เอาstring ลง textbox
            txtDateFrom.Text = sttimeFromnow;
            txtDateTo.Text = sttimetonow;

        }





        public void validationMMHH(TextBox stfromdate)
        {

            //ดักว่าต้อง pass ก่อนหน้าถึงมีสิทธิแทนที่ค่า   stvalidationMMHH
            if (stvalidationMMHH.Equals("PASS"))
            {

                // string stfromdate = txtDateFrom.Text;
                if (stfromdate.Text.Length == 5)
                {
                    string hh = stfromdate.Text.Substring(0, 2);
                    string mm = stfromdate.Text.Substring(3, 2);
                    string center = stfromdate.Text.Substring(2, 1);


                    int inthh;
                    int intmm;

                    if (int.TryParse(hh, out inthh))
                    {
                        if (inthh >= 0 && inthh <= 23)
                        {
                            if (int.TryParse(mm, out intmm))
                            {
                                if (intmm >= 0 && intmm <= 59)
                                {
                                    if (center.Equals(":"))
                                    {
                                        stvalidationMMHH = "PASS";
                                    }
                                    else
                                    {
                                        CommonMessageBox.ShowMessageWarning("กรุณาใส่ที่แบ่งชั่วโมงและนาทีให้เป็น :  เท่านั้น");
                                        stvalidationMMHH = "NO PASS";
                                        stfromdate.Focus();
                                    }
                                }
                                else
                                {
                                    CommonMessageBox.ShowMessageWarning("กรุณานาทีให้ถูกต้อง 0-59 เท่านั้น");
                                    stvalidationMMHH = "NO PASS";
                                    stfromdate.Focus();
                                }
                            }
                            else
                            {
                                CommonMessageBox.ShowMessageWarning("กรุณาใส่นาทีตัวเลขเท่านั้น");
                                stvalidationMMHH = "NO PASS";
                                stfromdate.Focus();
                            }
                        }

                        else
                        {
                            CommonMessageBox.ShowMessageWarning("กรุณาชั่วโมงให้ถูกต้อง 0-23 เท่านั้น");
                            stvalidationMMHH = "NO PASS";
                            stfromdate.Focus();
                        }
                    }

                    else
                    {
                        CommonMessageBox.ShowMessageWarning("กรุณาใส่ชั่วโมงตัวเลขเท่านั้น");
                        stvalidationMMHH = "NO PASS";
                        stfromdate.Focus();
                    }
                }


                else
                {
                    CommonMessageBox.ShowMessageWarning("กรุณาตรวจสอบความยาวของรูปแบบการกรอกข้อมูล");
                    stvalidationMMHH = "NO PASS";
                    stfromdate.Focus();
                }

                //จบดักว่าต้อง pass ก่อนหน้าถึงมีสิทธิแทนที่ค่า   stvalidationMMHH
            }

            else
            {
                //ไม่ต้องทำอะไร
            }

        }







        //ตรวจจับรูปแบบวันที่
        public void ConvertDate(string dateinput)
        {
            string dd = dateinput.Substring(8, 2);
            string mm = dateinput.Substring(5, 2);
            string yyyy = dateinput.Substring(0, 4);

            int yyyyint = Convert.ToInt32(yyyy);

            if (yyyyint > 2200)
            {
                yyyyint = yyyyint - 543;
            }

            else
            {
                //
            }

            string yyyyst = yyyyint.ToString();
            newdate = "" + yyyyst + "-" + mm + "-" + dd + "";

        }
        private void clearAll()
        {
              try
            {
                dgvTransaction.DataSource = null;
                txtAgentCode.Text = "";
                txtCarrier.Text = "";
                txtDateFrom.Text = "00:00";
                txtDateTo.Text = "23:59";
                txtFltNo.Text = "";
                txtHAWB.Text = "";
                txtPrefix.Text = "";
                txtScaleID.Text = "";
                txtSerial.Text = "";
                txtSlipNumber.Text = "";
                chkDataSearch.Checked = false;
                //dpkFlightDate.Value = DateTime.Now;
                dpkFromDate.Value = DateTime.Now;
                dpkToDate.Value = DateTime.Now;
                dpkFlightDate.Value = DateTime.Now;
                txtFltdate.Text = "";
                txtDevice.Text = "";
                txtUserID.Text = "";
                txtStationID.Text = "";
                txtAgentCode.Text = "";
                txtAgentName.Text = "";
                txtLocation.Text = "";
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        #endregion 

        private void btnAgentSearch_Click(object sender, EventArgs e)
        {
           // ValueTofrmAddMAWB.SelAgentCode = SelAgentCode;
           // ValueTofrmAddMAWB.SelAgentName = SelAgentName;
            try
            {
                frmAgentSearch a = new frmAgentSearch(null);
                if (a.ShowDialog() == DialogResult.Yes)
                {

                   // txtAgentCode.Text = ValueTofrmAddMAWB.SelAgentCode;
                    txtAgentCode.Text = ValueTofrmAddMAWB.SelAgentCode;
                    txtAgentName.Text = ValueTofrmAddMAWB.SelAgentName;

                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
    }
}
